﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using Lime;
using Clandestine.Base;

namespace Clandestine.Graphics.Text
{
    public class TextSprite : Sprite
    {
        private System.Drawing.Graphics grtmp;
        private System.Drawing.Font font;

        private string text;

        public string Text
        {
            get { return text; }
            set
            {
				// Early exit if someone is abusively setting Text to the same thing over and over.
				if (this.Texture != null && text == value)
					return;

                base.Graphics.BlockRendering();
                
                if (this.Texture != null)
                    this.Texture.Dispose();

                text = value;
                redrawText(value);
                    
                base.Graphics.UnblockRendering();
            }
        }

        internal TextSprite(RenderList list, System.Drawing.Graphics grtmp, System.Drawing.Font font, string text)
        	: base(list)
        {
            this.grtmp = grtmp;
            this.font = font;
			this.Color = Color4.White;

            this.Transform.ScaleUniform = 1f / Fonts.PrecisionScale;

            Text = text;
        }

        private void redrawText(string text)
        {
            Size size = grtmp.MeasureString(text, font).ToSize();

            if (size.IsEmpty)
                return;
			
			// Mono seems to be using premultiplied alpha or something even though our colour format pretty explicitly does
			//  not have premultiplied alpha.  So, we use a BitmapHelper command right now to restore correct RGB values. *shrugs*
			// It's harmless on Windows.

			System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
			
			sw.Start();
			
            // Here's where we do the hard work!
            Bitmap bmp = new Bitmap(size.Width, size.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp);
			//g.Clear(System.Drawing.Color.White);
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
            g.DrawString(text, font, Brushes.White, 0, 0);
            g.Flush(System.Drawing.Drawing2D.FlushIntention.Sync);
            g.Dispose();
			
			sw.Stop();
			
			Log.i("First pass text render took " + sw.ElapsedMilliseconds.ToString() + "ms.");
			
			sw.Reset();
			sw.Start();
			BitmapHelper.SetRGBToWhitePreserveAlpha(bmp);
			sw.Stop();
			Log.i("SetRGBToWhitePreserveAlpha() took " + sw.ElapsedMilliseconds.ToString() + "ms.");

            this.Texture = Graphics.Textures.AddBitmap(Guid.NewGuid().ToString(), bmp, false, true); // note: linear interpolation is ON.
        }
    }
}
